import * as EnumApi from "@/api/enum";
import * as UserApi from "@/api/user";
import * as UserEntityApi from "@/api/userEntity";
import * as MyApplyApi from "@/api/myApply";
import * as AuditApplyApi from "@/api/auditApply";
import * as ResourceTypeApi from "@/api/resourceType";
import * as ResourceTypeFieldApi from "@/api/resourceTypeField";
import * as ResourceTypeEntityApi from "@/api/resourceTypeEntity";
import * as ResourceTypeEntityDataApi from "@/api/resourceTypeEntityData";
import { applyStatus } from "@/config/settings";
import { dateFormat } from "@/utils/dateFormat";
import { mapGetters } from "vuex";

import ApplyInfoFormComponent from "@/views/pages/components/ApplyInfoForm";

export default {
  data() {
    return {
      // 是否展示所有申请列表
      allApplyListTable: false,

      // 申请信息列表
      applyInfoList: [],
      // 流程图获取地址
      processImageURL: "",
      // 申请状态
      applyStatus: {},

      // 分页设置
      layout: "total, sizes, prev, pager, next, jumper",
      pageData: {
        currentPage: 1,
        pageSize: 20,
        total: 0,
      },

      // 控制添加申请窗口显示与消失
      addApplyDialogVisible: false,
      //当前是添加还是修改 true:添加;false:修改
      addOrUpdate: false,

      //资源类别列表
      resourceTypeList: [],
      applyInfo: {},
      // 申请信息校验
      applyInfoRules: {
        applyType: [
          { required: true, message: "请选择申请方式", trigger: "change" },
        ],
        resourceTypeName: [
          { required: true, message: "请选择资源类别", trigger: "change" },
        ],
        applyReason: [
          { required: true, message: "请填写申请原因", trigger: "blur" },
        ],
        applyTime: [
          { required: true, message: "请选择申请时间", trigger: "blur" },
        ],
      },

      //控制设置备注窗口显示与消失
      setAdminRemarkDialogVisible: false,
      // 控制提前释放备注窗口显示与消失
      setAdvanceReleaseDialogVisible: false,
      // 控制分配阶段驳回请求备注弹窗显示与消失
      setRebackRemarkDialogVisible: false,
      // 控制仅修改申请信息弹窗显示与消失
      editApplyInfoDialogVisible: false,

      // 资源类别下动态字段信息
      resourceTypeEntityFieldList: [],

      // 用户列表
      userList: [],

      // 设置当前日期之前不可选
      pickerBeginDateBefore: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
    };
  },

  components: { ApplyInfoFormComponent },

  methods: {
    // 获取待审批申请信息列表
    getApplyInfoList() {
      AuditApplyApi.getApplyListInfoByAuditor().then((res) => {
        this.applyInfoList = res.data;
        this.applyInfoList.forEach((applyInfoItem) => {
          this.handleExpandChange(applyInfoItem, "");
        });
      });
    },

    // 切换到待审批申请列表
    changeToWaitAuditTable() {
      this.allApplyListTable = false;
      this.getApplyInfoList();
    },

    // 切换到所有申请信息列表
    changeToAllApplyTable() {
      this.allApplyListTable = true;
      AuditApplyApi.getApplyInfoList().then((res) => {
        this.applyInfoList = res.data;
        this.applyInfoList.forEach((applyInfoItem) => {
          this.handleExpandChange(applyInfoItem, "");
        });
      });
    },

    // 申请单展开触发事件
    handleExpandRow(row, expandedRows) {
      this.$refs.applyInfoList.toggleRowExpansion(row);
    },
    handleExpandChange(row, expandedRows) {
      if (!row.items && row.applyResourceId == 0) {
        this.getResourceCacheInfoById(
          row.resourceCacheInfoId,
          row.resourceTypeName
        );
      } else if (!row.items && row.applyResourceId != 0) {
        this.getResourceEntityInfoById(
          row.applyResourceId,
          row.resourceTypeName
        );
      }
    },
    // 通过缓存资源id获取缓存资源信息
    getResourceCacheInfoById(resourceCacheInfoId, resourceTypeName) {
      let self = this;
      MyApplyApi.getResourceCacheInfoById(resourceCacheInfoId).then((res) => {
        const index = self.applyInfoList.findIndex(
          (data) => data.resourceCacheInfoId === resourceCacheInfoId
        );
        ResourceTypeFieldApi.getResourceTypeFieldByName(resourceTypeName).then(
          (res) => {
            self.$set(self.applyInfoList[index], "entityFieldInfo", res.data);
          }
        );
        self.$set(
          self.applyInfoList[index],
          "items",
          JSON.parse(res.data.resourceEntityInfo)
        );
      });
    },
    // 通过资源实体id获取资源信息
    getResourceEntityInfoById(resourceTypeEntityId, resourceTypeName) {
      let self = this;
      ResourceTypeEntityDataApi.getResourceTypeEntityDataByEntityId(
        resourceTypeEntityId
      ).then((res) => {
        const index = self.applyInfoList.findIndex(
          (data) => data["applyResourceId"] == resourceTypeEntityId
        );
        ResourceTypeFieldApi.getResourceTypeFieldByName(resourceTypeName).then(
          (res) => {
            self.$set(self.applyInfoList[index], "entityFieldInfo", res.data);
          }
        );
        let entityFieldInfo = {};
        res.data.forEach((resourceEntityFieldValue) => {
          self.$set(
            entityFieldInfo,
            resourceEntityFieldValue.resourceTypeFieldName,
            resourceEntityFieldValue.resourceTypeEntityDataValue
          );
        });
        self.$set(self.applyInfoList[index], "items", entityFieldInfo);
      });
    },

    // 同意申请
    handleAgreeApply(index, row) {
      let param = {
        applyId: row.id,
        agree: true,
        remark: "同意申请",
      };
      AuditApplyApi.auditApply(param).then((res) => {
        this.showProcessMessage(res);
        if (res.code == 200) {
          if (row.applyResourceId != 0) {
            this.updateUserEntityRelation(row);
            let param = {
              resourceTypeEntityId: row.applyResourceId,
              status: "assign",
            };
            ResourceTypeEntityApi.updateResourceTypeEntityStatusById(
              param
            ).then((res) => {});
          }
        }
      });
    },
    // 更新用户实体关系
    updateUserEntityRelation(row) {
      UserApi.getUserInfoByUsername(row.applyBy).then((res) => {
        if (res.data != null) {
          let userEntity = {
            entityId: row.applyResourceId,
            userGroupName: res.data.userGroupName,
            username: res.data.username,
          };
          UserEntityApi.updateUserEntityByEntityId(
            userEntity
          ).then((res) => {});
        }
      });
    },
    // 驳回申请
    handleBackApply(index, row) {
      this.setAdminRemarkDialogVisible = true;
      this.applyInfo.id = row.id;
      this.applyInfo.applyResourceId = row.applyResourceId;
    },
    handleRebackApply() {
      let param = {
        applyId: this.applyInfo.id,
        agree: false,
        remark: this.applyInfo.adminRemark,
      };
      AuditApplyApi.auditApply(param).then((res) => {
        this.showProcessMessage(res);
        if (res.code == 200) {
          if (this.applyInfo.applyResourceId != 0) {
            let param = {
              resourceTypeEntityId: this.applyInfo.applyResourceId,
              status: "free",
            };
            ResourceTypeEntityApi.updateResourceTypeEntityStatusById(
              param
            ).then((res) => {});
          }
          this.setAdminRemarkDialogVisible = false;
        }
      });
    },

    // 分配阶段驳回申请
    // 驳回申请
    handleBackApplyInAssign(index, row) {
      this.setRebackRemarkDialogVisible = true;
      this.applyInfo.id = row.id;
      this.applyInfo.applyResourceId = row.applyResourceId;
    },
    handleRebackApplyInAssign() {
      let param = {
        applyId: this.applyInfo.id,
        agree: false,
        remark: this.applyInfo.adminRemark,
      };
      AuditApplyApi.rebackApply(param).then((res) => {
        this.showProcessMessage(res);
        if (res.code == 200) {
          if (this.applyInfo.applyResourceId != 0) {
            let param = {
              resourceTypeEntityId: this.applyInfo.applyResourceId,
              status: "free",
            };
            ResourceTypeEntityApi.updateResourceTypeEntityStatusById(
              param
            ).then((res) => {});
          }
          this.setRebackRemarkDialogVisible = false;
        }
      });
    },
    // 释放资源
    handleReleaseResource(index, row) {
      AuditApplyApi.freeResource(row.id).then((res) => {
        this.showProcessMessage(res);
        if (row.applyResourceId != 0) {
          let param = {
            resourceTypeEntityId: row.applyResourceId,
            status: "free",
          };
          ResourceTypeEntityApi.updateResourceTypeEntityStatusById(param).then(
            (res) => {
              if (row.resourceTypeName == "vm") {
                ResourceTypeEntityApi.markDeleteResourceTypeEntityByEntityId(
                  row.applyResourceId
                ).then((res) => {});
              }
            }
          );
        }
      });
    },
    // 提前释放资源
    handleAdvanceReleaseResourceDialog(index, row) {
      this.setAdvanceReleaseDialogVisible = true;
      this.applyInfo.id = row.id;
      this.applyInfo.applyResourceId = row.applyResourceId;
      this.applyInfo.resourceTypeName = row.resourceTypeName;
    },
    handleAdvanceReleaseResource() {
      let param = {
        applyId: this.applyInfo.id,
        agree: false,
        remark: this.applyInfo.adminRemark,
      };
      AuditApplyApi.advanceFreeResource(param).then((res) => {
        this.showProcessMessage(res);
        if (res.code == 200) {
          if (this.applyInfo.resourceTypeName == "vm") {
            ResourceTypeEntityApi.markDeleteResourceTypeEntityByEntityId(
              this.applyInfo.applyResourceId
            ).then((res) => {});
          }
          this.setAdvanceReleaseDialogVisible = false;
        }
      });
    },
    // 展示流程处理结果信息
    showProcessMessage(res) {
      if (res.code == 200) {
        this.$message.success(res.message);
        this.getApplyInfoList();
      } else {
        this.$message.error(res.message);
      }
    },

    // 解决输入框无法输入
    change(e) {
      this.$forceUpdate();
    },

    // 修改申请信息
    handleAssignDialog(index, row) {
      this.addApplyDialogVisible = true;

      this.applyInfo = row;
      this.$set(this.applyInfo, "applyTime", [
        row.applyStartUseTime,
        row.applyEndUseTime,
      ]);
    },

    // 仅修改申请信息弹窗
    handleEditInfoDialog(index, row) {
      this.editApplyInfoDialogVisible = true;

      this.applyInfo = row;
      this.$set(this.applyInfo, "applyTime", [
        row.applyStartUseTime,
        row.applyEndUseTime,
      ]);
    },
    // 仅仅修改申请信息
    handleEditApplyInfoResource() {
      this.formatterDate();
      let param = {
        applyInfo: this.applyInfo,
      };
      MyApplyApi.updateApplyInfo(param).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.editApplyInfoDialogVisible = false;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 处理日期参数
    formatterDate() {
      if (this.applyInfo.applyStartUseTime === this.applyInfo.applyTime[0]) {
        return;
      }
      this.$set(
        this.applyInfo,
        "applyStartUseTime",
        dateFormat(this.applyInfo.applyTime[0])
      );
      this.$set(
        this.applyInfo,
        "applyEndUseTime",
        dateFormat(this.applyInfo.applyTime[1])
      );
    },

    // 弹窗关闭
    closedDialog(dialogVisible) {
      this.addApplyDialogVisible = dialogVisible;
      this.getApplyInfoList();
    },

    // 获取实体数据列表数据
    getResourceTypeEntityDataList() {
      ResourceTypeEntityApi.getResourceTypeEntityListByName(
        this.applyInfo.resourceTypeName
      ).then((res) => {
        JSON.stringify;
        this.resourceTypeEntityDataList = res.data;
        // 获取资源实体动态字段数据
        this.getResourceTypeEntityFieldData();
      });
    },
    // 获取资源实体动态字段数据
    getResourceTypeEntityFieldData() {
      this.resourceTypeEntityDataList.forEach((element) => {
        ResourceTypeEntityDataApi.getResourceTypeEntityDataByEntityId(
          element.resourceTypeEntityId
        ).then((res) => {
          res.data.forEach((value) => {
            this.$set(
              element,
              value.resourceTypeFieldName,
              value.resourceTypeEntityDataValue
            );
          });
        });
      });
    },

    // 获取资源类别实体字段列表
    getResourceTypeEntityFieldList() {
      ResourceTypeFieldApi.getResourceTypeFieldByName(
        this.applyInfo.resourceTypeName
      ).then((res) => {
        this.resourceTypeEntityFieldList = res.data;
        this.resourceTypeEntityFieldList.forEach((fieldInfo) => {
          if (fieldInfo.resourceTypeFieldType == "enum") {
            EnumApi.getEnumItemByGroupName(fieldInfo.enumGroupName).then(
              (res) => {
                this.$set(fieldInfo, "enumItemList", res.data);
              }
            );
          }
        });
      });
    },

    // 获取资源类别列表
    getResourceTypeList() {
      ResourceTypeApi.getResourceTypeList().then((res) => {
        this.resourceTypeList = res.data;
      });
    },

    // 当前页发生改变
    handleCurrentChange(val) {
      this.pageData.currentPage = val;
    },
    // 当前页大小发生改变
    handleSizeChange(val) {
      this.pageData.pageSize = val;
    },

    getUserList() {
      UserApi.getUserList().then((res) => {
        this.userList = res.data;
      });
    },
    // 格式化用户名
    formatterUserNameToTitle(row, column, cellValue, index) {
      let value = cellValue;
      this.userList.forEach((userItem) => {
        if (userItem.username == value) {
          value = userItem.realName;
        }
      });
      return value;
    },

    // 长期使用
    usingLongTime() {
      let applyTime = [
        new Date(),
        new Date("9999-12-31 00:00:00".replace(/-/g, "/")),
      ];
      this.$set(this.applyInfo, "applyTime", applyTime);
    },

    // 表格样式设置
    getHeadClass({ rowIndex }) {
      if (rowIndex == 0) {
        return "background-color:#ccc;color:#fff;font-size:30px;";
      }
    },
    getRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 !== 0) {
        return "warning-row";
      }
    },
    allApplyClassName({ row, rowIndex }) {
      if (
        row.applyEndUseTime != "9999-12-31 12:00:00" &&
        Date.parse(new Date()) > Date.parse(row.applyEndUseTime)
      ) {
        return "error-row";
      }
    },
    showNull(row, column, cellValue) {
      if (cellValue === 0) {
        return "";
      } else {
        return cellValue;
      }
    },
  },

  computed: {
    ...mapGetters({
      userInfo: "user/userInfo",
    }),
  },

  mounted() {
    this.getResourceTypeList();
    this.processImageURL = MyApplyApi.getProcessImage;
    this.getApplyInfoList();
    this.applyStatus = applyStatus;
    this.getUserList();
  },
};
